<template>
    <div class="upload-box">
        <el-upload
            ref="upload"
            class="upload"
            :class="{ 'hide-close': !show }"
            :limit="limit"
            multiple
            drag
            :accept="accept"
            :action="action"
            :headers="headers"
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :on-preview="handleDownload"
        >
            <!-- <el-button v-if="show" slot="trigger" type="text" size="small" icon="el-icon-receiving">选择文件</el-button> -->
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em> 点击上传</em></div>
            <div slot="tip" class="el-upload__tip" style="display: flex; align-items: flex-start;"><i class="el-icon-info" style="padding: 3px 4px 0 0;"></i> <span v-html="tips"></span> </div>
        </el-upload>
    </div>
</template>

<script>
import { UploadOption, ResponseCode } from '@/config/constants'
import { getToken } from '@/utils/auth'
import { MaintenanceProjectModel } from '@/models'
import { fileTokenKey } from '@/config/settings'
export default {
    name: 'FileUpload',
    props: {
        list: {
            type: Array,
            default: () => []
        },
        show: {
            type: Boolean,
            default: true
        },
        limit: {
            type: Number,
            default: 9
        },
        size: {
            type: Number,
            default: 50
        },
        tips: {
            type: String,
            default: '最多上传9个文件，单个文件最多50M，支持：.rar .zip .pdf .doc .docx  .xls .xlsx .jpg .jpeg .png 格式。'
        },
        accept: {
            type: String,
            default: '.rar,.zip,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,image/jpeg,image/png'
        },
        fileRuleType: {
            type: Array,
            // 限制选择的文件类型和再次验证的不一样，如有必要，需要定义两遍类型
            default: () => ['rar', 'zip', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'png']
        }
    },
    data() {
        return {
            model: new MaintenanceProjectModel(),
            action: UploadOption.ACTION,
            headers: {
                [fileTokenKey]: getToken()
            },
            fileList: [],
            files: [],
            messageQueue: [],
            isMessageShowing: false
        }
    },
    watch: {
        files: {
            handler(newval) {
                const disabled = newval.some((item) => item.status && item.status !== 'success')
                this.$emit('load', disabled)
            },
            deep: true
        },
        // 监听回传的文件列表
        list: {
            handler(newval) {
                this.fileList = newval
                this.files = this.fileList
            },
            deep: true
        }
    },
    methods: {
        handleDownload(file) {
            const url = file.url || file.response.data.objectUrl
            const a = document.createElement('a')
            a.href = url
            a.download = file.name
            document.body.appendChild(a)
            a.click()
            // 把a标签删除，减少dom节点冗余
            document.body.removeChild(a)
        },
        handleExceed(files) {
            this.$message.warning(`最多上传${this.limit}个文件，本次选择了 ${files.length} 个文件`)
        },
        handleBeforeUpload(file) {
            // 如果files里有相同name文件，说明已经上传过同名文件
            const length = this.files.filter((item) => item.name === file.name).length
            if (length >= 2) {
                // 将消息添加到队列中
                this.messageQueue.push({
                    message: `已经上传相同名称文件${file.name}`,
                    timeoutId: null
                })
      
                // 如果当前没有消息正在显示，开始显示队列中的第一个消息
                if (!this.isMessageShowing) {
                    this.showNextMessage()
                }
                // this.$message.error(`已经上传相同名称文件${file.name}`)
                return false
            }
            
            // 文件大于50MB的禁止上传
            if (file.size / 1024 / 1024 > this.size) {
                this.$message.error(`文件${file.name}大小超过${this.size}MB`)
                return false
            }
            console.log(file)
            // 文件扩展名限制格式
            const fileType = file.name.split('.').pop().toLowerCase()
            if (!this.fileRuleType.includes(fileType)) {  
                this.$message.error('上传文件格式不正确!')  
                return false  
            }
            return true
        },
        isFileDuplicated(file) {
            // 这里实现你的文件重复检查逻辑
            // ...
            return true // 示例中直接返回 true
        },

        showNextMessage() {
            // 设置标志位，表示现在有消息正在显示
            this.isMessageShowing = true

            // 获取队列中的第一个消息
            const messageInfo = this.messageQueue.shift()

            // 设置定时器，在 500 毫秒后显示消息
            messageInfo.timeoutId = setTimeout(() => {
                this.$message({
                    message: messageInfo.message,
                    type: 'error',
                    duration: 4000
                })

                // 定时器结束后，检查队列中是否有更多消息等待显示
                clearTimeout(messageInfo.timeoutId) // 清除定时器，防止内存泄漏
                if (this.messageQueue.length > 0) {
                    this.showNextMessage() // 显示下一个消息
                } else {
                    // 如果队列为空，重置标志位
                    this.isMessageShowing = false
                }
            }, 500)
        },
        handleChange(file, fileList) {
            this.files = fileList
        },
        handleRemove(file) {
            this.files.some((item, index) => {
                if (item.uid === file.uid) {
                    this.files.splice(index, 1)
                    return true
                }
            })
        },
        handleSuccess(response, file, fileList) {
            if (response.code === ResponseCode.success) {
                this.files = fileList
            } else {
                fileList.some((item, index) => {
                    if (item.uid === file.uid) {
                        fileList.splice(index, 1)
                        return true
                    }
                })
                this.$message.error('文件上传失败，请重试！')
            }
        },
        handleError() {
            this.$message.error('网络异常，请稍后再试!')
        },
        getFileList() {
            const annexList = this.files.map((item) => {
                return {
                    name: item.name,
                    url: item.url || item.response.data.objectUrl
                }
            })
            return annexList
        }
    }
}
</script>

<style lang="scss" scoped>
.upload-box {
    position: relative;
    width: 700px;
    margin-top: 24px;
    .upload {
        position: relative;
        z-index: 20;
        ::v-deep {
            .el-upload-list {
                margin-bottom: 24px;
            }
        }
    }
    .spe-title {
        position: absolute;
        top: 5px;
        z-index: 10;
    }
    .hide-close {
        ::v-deep .el-icon-close {
            display: none;
        }
    }
}
</style>
